<template>
  <div>
    <div
      v-show="initData.length"
      :id="id"
      style="width: 100%;height: 200px;"
    ></div>
    <div v-if="!initData.length" class="noData">暂无数据</div>
  </div>
</template>

<script>
import * as echarts from "echarts";
import { Color } from '@/utils/colorVariate'
export default {
  data() {
    return {
      myChart: null
    };
  },
  props: {
    id: {
      type: String,
      default: 'pie'
    },
    initData: {
      type: Array,
      default: () => []
    }
  },
  mounted() {
    if(this.initData.length) {
      this.$nextTick(() => {
        this.initMap();
      })
    }
  },
  watch: {
    initData: {
      handler(val) {
        this.$nextTick(() => {
          this.initMap();
        })
      }
    }
  },
  methods: {
    initMap() {
      if(!this.initData.length) return 
      const _this = this
      const chartDom = document.getElementById(this.id);
      this.myChart = echarts.init(chartDom);
      this.myChart.showLoading();

      let option = {
        tooltip: {
          trigger: "item",
        },
        color: Color,
        series: [
          {
            type: "pie",
            radius: ['30%', '90%'],
            itemStyle: {
              borderRadius: 10,
              borderColor: '#fff',
              borderWidth: 2
            },
            data: this.initData, 
            emphasis: {
              itemStyle: {
                shadowBlur: 10,
                shadowOffsetX: 0,
                shadowColor: "rgba(0, 0, 0, 0.5)",
              },
            },
            label: {
              show: true,
              position: 'inner',
              formatter: '{b}：{d}%', // 格式化数值百分比输出
            }
          }
        ],
      };

      option && this.myChart.setOption(option);
      this.myChart.hideLoading();
      window.addEventListener("resize", function() {
        _this.myChart.resize();
      });
    },
  },
  beforeDestroy() {
    if (this.myChart) {
      this.myChart.clear();
    }
  }
};
</script>

<style lang="less" scoped>
.noData {
  display: flex;
  justify-content: center;
  align-items: center;
  width: 100%;
  height: 200px;
  font-size: 16px;
  font-weight: 700;
}
</style>  
